<template>
  <div class="employees-container">
    <div class="app-container">

      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <page-tools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总计{{ total }}条数据</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <!-- <el-button v-if="canClick('exportExcel')" type="primary" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button v-if="canClick('OUT')" :loading="downloadLoading" type="primary" size="small" @click="exportData">导出excel</el-button>
              <el-button v-if="canClick('p-em-add')" type="primary" size="small" @click="showDialog = true">新增员工</el-button> -->
              <el-button type="primary" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button :loading="downloadLoading" type="primary" size="small" @click="exportData">导出excel</el-button>
              <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
            </template>
          </page-tools>

        </div>
        <!-- 页面内容 -->
        <div>
          <el-table border :data="list" :default-sort="{prop: 'workNumber', order: 'descending'}">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column label="头像">
              <template #default="{row}">
                <el-image class="photo" :src="row.staffPhoto" fit="cover" @click="clickShowDialog(row.staffPhoto)"></el-image>
              </template>
            </el-table-column>

            <el-table-column prop="workNumber" label="工号" />
            <el-table-column prop="formOfEmployment" label="聘用形式">
              <template #default="{ row }">
                {{ formatFormOfEmployment(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column sortable prop="correctionTime" label="入职时间">
              <template #default="{ row }">
                {{ formDate(row.correctionTime) }}
              </template>
            </el-table-column>
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
                <!-- <el-button v-if="canClick('p-em-look')" type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button> -->
                <el-button v-if="canClick('FP')" type="text" size="small" @click="openRole(row.id)">分配角色</el-button>
                <el-button v-if="canClick('laowang-dele')" type="text" size="small" @click="delEmploy(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <el-pagination background :total="total" :current-page="query.page" :page-size="query.size" :page-sizes="[2,5,10]" layout="prev, pager, next, sizes" @current-change="changePage" @size-change="changeSize" />
          </el-row>
        </div>
      </el-card>

    </div>
    <AddEmployee :show-dialog.sync="showDialog" />
    <el-dialog title="二维码" :visible.sync="showCodeDialog" width="30%" @close="showCodeDialog = false">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>

    </el-dialog>
    <!-- 添加分配角色弹框 -->
    <assignRole ref="ar" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>
<script>
import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import diction from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import QrCode from 'qrcode'
import assignRole from './components/assign-role.vue'
// import { formDate } from '@/utils/changeDate'
export default {
  components: {
    PageTools,
    AddEmployee,
    assignRole
  },
  data () {
    return {
      showRoleDialog: false,
      showCodeDialog: false,
      downloadLoading: false,
      showDialog: false,
      qy: true,
      list: [],
      query: {
        page: 1,
        size: 10
      },
      total: 10
    }
  },
  created () {
    this.getList()
  },
  methods: {
    formDate(date, flag = '-') {
      if (!date) return ''
      const newDate = new Date(date)
      const year = newDate.getFullYear()
      let month = newDate.getMonth() + 1
      let day = newDate.getDay()
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) day = '0' + day
      return year + flag + month + flag + day
    },
    openRole (id) {
      this.showRoleDialog = true
      this.$refs.ar.getUserRoles(id)
    },
    // 格式化员工聘用形式
    formatFormOfEmployment (type) {
      const map = {}
      diction.hireType.forEach((item) => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 获取员工数据列表
    async getList () {
      const { rows, total } = await getEmployeeList(this.query)
      // console.log(rows)
      this.list = rows
      this.total = total
    },
    // 翻页触发的函数
    changePage (page) {
      this.query.page = page
      this.getList()
    },
    // 改变每页条数触发函数
    changeSize (size) {
      this.query.size = size
      this.getList()
    },
    // 删除员工
    async delEmploy (row) {
      try {
        this.$confirm(`确定要删除：${row.username}吗？`)
        await delEmployee(row.id)
        const newPage = Math.ceil((this.total - 1) / this.query.size)
        if (this.query.page > newPage) {
          // 纠正页码
          this.query.page = newPage
        }
        this.getList()
        this.$message.success('删除成功！')
      } catch (error) {
        console.log(error)
      }
    },
    async exportData () {
      this.downloadLoading = true
      const excel = await import('@/utils/Export2Excel')
      // console.log(excel)
      const { header, secondArry } = this.filterData()
      // const header = ['姓名', '工资', '性别']
      // const data = secondArry
      excel.export_json_to_excel({
        header, // 导出数据表头
        data: secondArry, // 导出数据
        filename: `导出第${this.query.page}页数据`,
        autoWidth: true, // 单元格是否自适应
        bookType: 'xlsx'
      })
      this.downloadLoading = false
    },
    filterData () {
      const exportMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(exportMap)
      // 指出导出属性名
      const filterkeys = Object.values(exportMap)
      const secondArry = []
      this.list.forEach(item => {
        const userInfo = []
        for (const key in item) {
          if (filterkeys.includes(key)) {
            if (key === 'formOfEmployment') {
              userInfo.push(this.formatFormOfEmployment(item[key]))
            } else {
              userInfo.push(item[key])
            }
          }
        }
        secondArry.push(userInfo)
      })
      return { header, secondArry }
    },
    clickShowDialog (url) {
      if (!url) return
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.photo {
  height: 80px;
  width: 80px;
  border-radius: 100%;
}
</style>
